<template>
  <div class="addGood">
    <el-alert
      title="添加商品信息"
      type="info"
      show-icon
      center
      :closable="false"
    ></el-alert>

    <!-- 步骤条 -->
    <el-steps
      :space="200"
      :active="activeIndex"
      finish-status="success"
      align-center
    >
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>

    <el-form
      :model="addForm"
      :rules="rules"
      ref="addForm"
      label-width="100px"
      label-position="top"
    >
      <el-tabs tab-position="left" :before-leave="beforeTabLeave" value="0">
        <!-- @tab-click="tabClick" -->
        <!-- 1111 -->
        <el-tab-pane label="基本信息" name="0">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :on-change="imgChange"
          >
            <img v-if="goodImg" :src="goodImg" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input
              v-model="addForm.goods_price"
              type="number"
              min="0"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input
              v-model="addForm.goods_number"
              type="number"
              min="0"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input
              v-model="addForm.goods_weight"
              type="number"
              min="0"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="addForm.goods_cat"
              :options="GoodCategory"
              :props="{
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
              }"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <!-- 222  ==============================================================-->
        <el-tab-pane label="商品参数" name="1">
          <el-form-item
            v-for="item in manyAttribute"
            :key="item.attr_id"
            :label="item.attr_name + item.attr_id"
          >
            <el-checkbox-group
              v-model="addForm.selectedManyAttribute[item.attr_id]"
            >
              <el-checkbox
                v-for="(item2, index) in item.attr_vals"
                :key="index + 10"
                :label="item2"
                checked
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <!-- 333 -->
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            v-for="item in onlyAttribute"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-input :value="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <!-- 444 -->
        <el-tab-pane label="商品内容" name="3">
          <!-- 富文本编辑器组件 -->
          <quill-editor v-model="addForm.goods_introduce"></quill-editor>
          <!-- 添加商品的按钮 -->
          <el-button type="primary" class="addBtn" @click="addGoods"
            >添加商品</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </div>
</template>

<script>
import { getGoodCategory, getGoodAttribute, addGood } from "@/api/goods";

export default {
  name: "addGood",
  data() {
    var goods_cat_check = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error("必须选择商品分类"));
      } else if (value.length != 3) {
        callback(new Error("三类商品类别必须选全"));
      } else {
        callback();
      }
    };
    return {
      activeIndex: 0,
      addForm: {
        goods_name: "测试1",
        goods_price: 99,
        goods_number: 99,
        goods_weight: 99,
        goods_cat: [],
        goods_introduce: "", // 商品的详情
        selectedManyAttribute: { 3077: [] },
        selectedOnlyAttribute: [],
        goods_img: null,
      },
      goodImg: "",
      manyAttribute: [],
      onlyAttribute: [],
      rules: {
        //这个是自定义的检测 （用户名可能已经存在）
        goods_name: [{ required: true, message: "必须填写", trigger: "blur" }],
        goods_price: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { min: 1, message: "价格不能为0", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入数量", trigger: "blur" },
          { min: 1, message: "数量不能为0", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入重量", trigger: "blur" },
          { min: 1, message: "重量不能为0", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, validator: goods_cat_check, trigger: "blur" },
        ],
      },
      GoodCategory: [],
    };
  },
  watch: {
    //监视添加商品中的goods_cat（选中的三级）
    "addForm.goods_cat": {
      // deep: true,
      handler(newValue, oldValue) {
        // console.log(newValue);
        //三级id
        newValue.length === 3 &&
          getGoodAttribute(newValue[2]).then(
            (res) => {
              // console.log(res);
              if (res.data.status === 200) {
                //存放属性
                this.manyAttribute = res.data.data.manyAttribute;
                //动态添加selectedManyAttribute的属性 每一个[]都独立存放many
                this.addForm.selectedManyAttribute = {};
                Object.keys(this.manyAttribute).forEach((key) => {
                  this.$set(
                    this.addForm.selectedManyAttribute,
                    this.manyAttribute[key].attr_id,
                    []
                  );
                });

                this.onlyAttribute = res.data.data.onlyAttribute;
                this.addForm.selectedOnlyAttribute = this.onlyAttribute;
              }
            },
            (err) => {
              console.log(err);
            }
          );
      },
    },
  },
  created() {
    this.initGoodCategory();
  },

  methods: {
    initGoodCategory() {
      getGoodCategory().then(
        (res) => {
          // console.log(res.data);
          if (res.data.status === 200) {
            this.GoodCategory = res.data.data;
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },

    beforeTabLeave(activeName, oldActiveName) {
      // console.log(activeName, oldActiveName);
      // console.log("+++++", this.addForm.selectedManyAttribute);

      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$nextTick(() => {
          this.$refs["addForm"].validate(() => {});
        });
        return false;
      } else {
        //填写完成 下一步
        this.activeIndex = activeName - 0;
        //返回清空检测
        if (activeName === "0") {
          this.$refs["addForm"] && this.$refs["addForm"].clearValidate();
        }
      }
    },
    imgChange(file, fileList) {
      // console.log(file.raw.type);
      const ImgForm =
        file.raw.type === "image/jpeg" || file.raw.type === "image/png";
      const isLt2M = file.raw.size < 1024 * 1024 * 2; //小于2M

      if (!ImgForm)
        return this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      if (!isLt2M) return this.$message.error("上传头像图片大小不能超过 2MB !");

      //得到本地图像(详细见md)
      this.goodImg = URL.createObjectURL(file.raw);
      this.addForm.goods_img = file.raw;
    },
    addGoods() {
      //放入formData
      let fd = new FormData();
      Object.keys(this.addForm).forEach((key) => {
        if (key === "goods_img") {
          fd.append("goods_img", this.addForm[key]);
        } else fd.append(key, JSON.stringify(this.addForm[key]));
      });
      // console.log(this.addForm);
      //添加成功
      this.activeIndex = 5;
      addGood(fd).then(
        (res) => {
          if (res.data.status === 200) {
            this.$message.success("添加成功");
            //发送告知刷新页面
            this.$bus.$emit("searchChange", "");
            //跳转到列表页面
            setTimeout(() => {
              this.$router.push("/goods");
            }, 1000);
          } else if (res.data.status === 1063) {
            this.$message.error("商品名称重复");
          }
        },
        (err) => {
          this.$message.error("添加失败");
        }
      );
    },
  },
};
</script>

<style  scoped>
.addGood {
  position: relative;
  overflow: hidden;
  padding: 20px;
}
.el-alert {
  margin-bottom: 20px;
}
.el-steps {
  margin-bottom: 20px;
}
.el-input {
  width: 95%;
}

::v-deep .el-form-item__label {
  padding: 0;
}
.el-form-item {
  margin-bottom: 20px;
}
/*  */
.avatar-uploader {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 210px !important;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  border: 1px dashed #c6c2c2;
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  width: 200px;
  height: 200px;
  display: block;
}
.addBtn {
  margin-top: 15px;
}
::v-deep .ql-editor {
  height: 250px;
}
</style>
